#!/usr/bin/env sh

get_sed()
{
	while read LINE
	do
		argit=$(echo "$LINE"|cut -d " " -f 1);
		chgit=$(echo "$LINE"|cut -d " " -f 2);
		echo -n "sed -E 's/%%$argit(.*)?%%/$chgit/g' |";
	done < $1
	echo "cat -";
}

templatedir=~/.templates;
rpcfile="";
while getopts f:r:t: option
do
	case "$option" in
		'r') rpcfile="$OPTARG";;
		't') template="$OPTARG";;
	esac
done

if [ -z "$template" ]
then
	echo "Missing template" >/dev/stderr;
	return 0;
fi
echo "Template: $templatedir/$template" > /dev/stderr;

if [ ! -e $templatedir/$template ]
then
	echo "Invalid template" >/dev/stderr;
	exit 1;
fi

if [ -n "$rpcfile" ]
then
	cmd=$(get_sed "$rpcfile");
	echo "$cmd";
	cat "$templatedir/$template"|$cmd;
fi

cat "$templatedir/$template";
exit 0;